package com.example.springlearn.controller;

import com.example.springlearn.bean.AnsInfo;
import com.example.springlearn.service.AnsService;
import com.example.springlearn.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Controller
@RequestMapping(value = "/home")
public class HomePageController {

    @Autowired
    AnsService ansService;

    @GetMapping("/space")
    public String space(ModelMap map, @CookieValue("username") String username, @CookieValue("uid") String uid) {

        if (username == null || uid == null) {
            return "forward:/";
        }

        List<AnsInfo> ansInfos = ansService.queryGradesByUserId(Integer.parseInt(uid));

        map.addAttribute("username", username);
        map.addAttribute("ans", ansInfos);

        return "/home/space";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = CookieUtil.delCookies(req.getCookies());

        for (Cookie cookie : cookies) {
            resp.addCookie(cookie);
        }
        return "redirect:/";
    }

}
